<template>
  <div class="employees-container">
    <div class="app-container">
      <PageTools>
        <template #left>
          <span>总记录数: {{ total }}条</span>
        </template>

        <template #right>
          <el-button v-if="checkBtnAccess('POINT_EXCEL_IMPORT')" type="warning" size="small" @click="$router.push('import?type=user')">excel导入</el-button>
          <el-button v-if="checkBtnAccess('POINT_EXCEL_EXPORT')" type="danger" size="small" @click="handleExportExcel">excel导出</el-button>
          <el-button type="primary" size="small" @click=" clickAdd">新增员工</el-button>
        </template>
      </PageTools>

      <el-card style="margin-top: 10px;">
        <el-table v-loading="loading" border :data="list">
          <el-table-column label="序号" type="index" :index="indexMethod" sortable="" />
          <el-table-column label="头像" prop="staffPhoto" sortable>
            <template #default="{ row }">
              <img v-imgerror="errorImg" class="staffPhoto" :src="row.staffPhoto || defaultPhoto" alt="" @click="handleImgClick(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="手机号" prop="mobile" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formatEmployment" sortable="" />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" sortable="">
            <template #default="{ row }">
              {{ row.timeOfEntry | formmatData }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" :disabled="!checkBtnAccess('POINT_USER_EDIT')" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" :disabled="!checkBtnAccess('POINT_USER_JUESE')" @click="handleRoleAssign(row.id)">角色</el-button>
              <el-button type="text" size="small" :disabled="!checkBtnAccess('POINT_USER_DELETE')" @click="del(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->

        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :total="total"
            :current-page="page"
            :page-sizes="[1,2,3,4,5,6,7,8,9,10]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
      <AssignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
      <AddEmployee :show-dialog.sync="isShow" @add-employee="getEmployeeList" />

      <el-dialog
        width="400px"
        title="二维码预览"
        :visible="show2WeiCode"
        @close="show2WeiCode = false"
      >

        <!-- 二维码 必须 放在canvas html5原生标签: 画布(你画我猜) 绘制复杂图像 -->
        <!-- ref 获取dom / 组件 -->
        <div style="text-align: center">
          <canvas ref="myCanvas" />
        </div>
      </el-dialog>

    </div>
  </div>
</template>

<script>
import QrCode from 'qrcode'
import errorImg from '@/assets/common/bigUserHeader.png'
import AddEmployee from './components/AddEmployee.vue'
import AssignRole from './components/AssignRole.vue'
import obj from '@/constant/employees'
import PageTools from '@/components/Pagetools'
import { reqDelEmployee, reqGetEmployeeList } from '@/api/employees'
import moment from 'moment'
import check from '@/mixins/check'
// import { reqGetSimpleUserList } from '@/api/user'
// import moment from 'moment'
export default {
  components: {
    PageTools,
    AddEmployee,
    AssignRole

  },
  mixins: [check],
  data() {
    return {
      errorImg,
      list: [],
      page: 1,
      pageSize: 5,
      total: 0,
      loading: false,
      userId: '',
      showRoleDialog: false,
      isShow: false,
      defaultPhoto: 'https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2146034403,1504718527&fm=26&gp=0.jpg',
      show2WeiCode: false
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    clickAdd() {
      if (!this.checkBtnAccess('POINT_USER_ADD')) {
        this.$message.error('你没有权限，努力吧打工人')
        return
      }
      this.isShow = true
    },
    async getEmployeeList() {
      this.loading = true
      const { data: { total, rows }} = await reqGetEmployeeList(this.page, this.pageSize)
      this.list = rows
      this.total = total
      this.loading = false
    },
    handleCurrentChange(val) {
      // val 页码
      this.page = val
      this.getEmployeeList()
    },
    handleSizeChange(val) {
      // val 用户自己选择的每页条数
      this.pageSize = val

      // 回到第一页
      this.page = 1

      // 获取数据
      this.getEmployeeList()
    },
    indexMethod(index) {
      return index + 1 + this.pageSize * (this.page - 1)
    },
    formatEmployment(row, column, cellValue, index) {
      const arr = obj.hireType
      const res = arr.find(item => item.id === +cellValue)
      return res ? res.value : '未知'
    },
    del(id) {
      this.$confirm('确定要删除该员工吗', '温馨提示').then(async() => {
        await reqDelEmployee(id)
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }
        this.$message.success('删除成功')
        this.getEmployeeList()
      }).catch(() => {
        console.log('取消了')
      })
    },
    async handleExportExcel() {
      const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 原数据 => [{}, {}, {}, ...]
      const { data: { rows }} = await reqGetEmployeeList(1, this.total)
      console.log(rows, 888)
      const result = this.transOriginTo2Wei(rows, headersArr, headersRelations)
      console.log(result, 777)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: headersArr, // 表格的头部
          // 二维数组 [ [], [], [] ]
          data: result,
          filename: '学生信息表' // 导出的excel文件名
        })
      })
    },
    transOriginTo2Wei(rows, headersArr, headersRelations) {
      // [
      //   [ 值1, 值2, 值3, ... ]
      // ]
      // console.log(rows)
      // console.log(headersArr)
      const arr = []
      rows.forEach(item => {
        const res = []
        headersArr.forEach(key => {
          // console.log(key)
          const englishKey = headersRelations[key]
          // console.log(item[englishKey], 999)
          let val = item[englishKey]
          if (englishKey === 'formOfEmployment') {
            const { hireType } = obj
            const resObj = hireType.find(v => v.id === +val)
            val = resObj ? resObj.value : '未知'
          }
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            val = moment(val).format('YYYY年MM月DD日')
          }
          res.push(val)
        })
        arr.push(res)
      })
      return arr
    },
    handleImgClick(url) {
      if (!url) return
      this.show2WeiCode = true
      this.$nextTick(() => {
        QrCode.toCanvas(this.$refs.myCanvas, url)
      })
    },
    handleRoleAssign(id) {
      this.showRoleDialog = true
      this.userId = id
    }
  }

}
</script>

<style lang="scss" scoped>
.employees-container {
  .staffPhoto {
    width: 70px;
    height: 70px;
    border-radius: 50%;
  }
}
</style>
